from flask import Blueprint, render_template, redirect, url_for, request, flash
from flask_login import login_user, logout_user, login_required
from werkzeug.security import generate_password_hash, check_password_hash
from app.models.models import Users
from app import db

auth = Blueprint('auth', __name__)



@auth.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        print(1111)
        user = Users.query.filter_by(username=username).first()

        if not user or not check_password_hash(user.password, password):
            print("登陆失败，账号或密码错误")
            flash('Invalid username or password.')
            return redirect(url_for('auth.login'))

        print("登陆成功")

        login_user(user)
        if user.role == 'admin':
            return redirect(url_for('main.dashboard'))
        elif user.role == 'teacher':
            return redirect(url_for('main.dashboard'))
        elif user.role == 'student':
            return redirect(url_for('main.dashboard'))
        else:
            return redirect(url_for('main.index'))

    return render_template('user/login.html')

@auth.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('main.index'))
